//
//  PingTransation.swift
//  PingTransition
//
//  Created by tianqi on 2017/11/9.
//  Copyright © 2017年 david.com. All rights reserved.
//

import UIKit

class PingTransition:NSObject, UIViewControllerAnimatedTransitioning {
    
    var transitionContext: UIViewControllerContextTransitioning?
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.7
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        self.transitionContext = transitionContext
        
        let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as! ViewController
        let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as! ViewController2
//        transitionContext.containerView.addSubview(fromVC.view)
        transitionContext.containerView.addSubview(toVC.view)

        // 开始和结束圆路径
        
        let startBezierPath = UIBezierPath(ovalIn: fromVC.button.frame)
        
        let dx = fromVC.button.center.x
        let dy = fromVC.view.bounds.height - fromVC.button.center.y
        
        let redius: CGFloat = sqrt(dx * dx + dy * dy) + 30
        let rect = fromVC.button.frame.insetBy(dx: -redius, dy: -redius)
        let endBezierPath = UIBezierPath(ovalIn: rect)
        
        // toVC.view增加 mask
        
        let mask = CAShapeLayer()
//        mask.path = endBezierPath.cgPath
        toVC.view.layer.mask = mask
        
        // mask 添加动画
        
        let animation = CABasicAnimation(keyPath: "path")
        animation.fromValue = startBezierPath.cgPath
        animation.toValue = endBezierPath.cgPath
        animation.duration = 0.7
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        animation.delegate = self
        mask.add(animation, forKey: "ping")
        
        
    }
}

extension PingTransition:CAAnimationDelegate {
    
    func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
        // 告诉系统专场结束
        let isfinished = self.transitionContext?.transitionWasCancelled
        self.transitionContext?.completeTransition(!isfinished!)
        // 清除mask
        self.transitionContext?.view(forKey: UITransitionContextViewKey.to)?.layer.mask = nil
        self.transitionContext?.view(forKey: UITransitionContextViewKey.from)?.layer.mask = nil
    }
}






